package com.ebupt.migu.music.common.interceptor;

import com.ebupt.migu.music.common.auth.AuthConst;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.TokenUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: workorder
 * @description: header 安全认证 拦截器
 * @author: zhanggk
 * @create: 2019-02-28 13:24
 **/
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    /**
     * 进入controller层之前拦截请求
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            String token = request.getHeader("token");
//            String token = request.getSession().getAttribute(AuthConst.TOKEN).toString();
            // 获取表中的token
            log.debug("获取到的token:[{}]", token);

            // 判断正式是否为空
            if (StringUtils.isBlank(token)) {
                throw new MyException(StatusEnum.TOKEN_NULL, "非法登陆");
            }
            Claims claims = TokenUtils.parseJWT(token);
            // 判断证书是否超时
            if(claims.getExpiration().getTime() < System.currentTimeMillis()){
                throw new MyException(StatusEnum.TOKEN_INVALID, "token失效，请重新登陆");
            }
            return true;
        }catch (Exception e){
            log.error("安全认证失败：[{}]", e.getMessage());
            throw new MyException(StatusEnum.USER_VERIFICATION_FAILED, e.getMessage());
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
    }
}